<template>
    <div>
        <Spin fix v-if="ifSpin">
            <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
            <div>附件生成中</div>
        </Spin>
        <Form :label-width="80" ref="formInline" :model="formInline">
            <Row :gutter="16" class="query-form2">
                <i-col span="8">
                    <FormItem label="单位：" prop="se_date">
                        <cascaderDom ref="existOrg" @setOrgInfo="setOrgName" :orgTree="true" :currentOrgId = "dataToView.companyId" :currentOrgName = "dataToView.companyName" :setCurrentName="{value:dataToView.companyId, label:dataToView.companyName}"></cascaderDom>
                    </FormItem>
                </i-col>
                <i-col span="8">
                    <FormItem label="时间：" prop="se_date">
                        <DatePicker v-model="formInline.se_date" type="datetimerange" style="width: 100%" format="yyyy-MM-dd" placeholder="请选择查询时间（开始，结束）"></DatePicker>
                    </FormItem>
                </i-col>
                <i-col span="8">
                    <div style="float: right;">
                        <Button class="ivu-btn-query"  icon="md-search"  @click="query">查询</Button>
                        <Button class="ivu-btn-reset" style="margin-left: 10px" @click="cancel">重置</Button>
                    </div>
                </i-col>
            </Row>
        </Form>
        <Row type="flex" justify="start" class="query-form">
            <i-col>
                <Button icon="md-cloud-download" class="ivu-btn-add" @click="exportExcel">导出</Button>
            </i-col>
        </Row>
        <Table ref='table' style="margin-top: 10px" :loading="loading" border :columns="columns" no-data-text="没有查询到相关数据！"
               :data="infos" width="100%" :height="tableHeight" highlight-row stripe size="small"></Table>
    </div>
</template>

<script>
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import {sessionStorage} from '@/common/cacheUtils.js';
    import {Api} from '../../../api'

    export default {
        name: "investigationCount",
        components:{
            cascaderDom
        },
        data(){
            return {
                loading: false,
                ifSpin: false,
                tableHeight: '',
                formInline: {
                    se_date: []
                },
                columns: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        align: 'center',
                        fixed: 'left',
                    },
                    {
                        title: '所属公司',
                        align: 'center',
                        key: 'parentOrgName',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.parentOrgName || '--')
                            ]);
                        }
                    },
                    {
                        title: '项目部',
                        align: 'center',
                        key: 'orgName',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.orgName || '--')
                            ]);
                        }
                    },
                    {
                        title: '隐患编号',
                        align: 'center',
                        key: 'name',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.name || '--')
                            ]);
                        }
                    },
                    {
                        title: '专业',
                        align: 'center',
                        key: 'type',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.type || '--')
                            ]);
                        }
                    },
                    {
                        title: '排查类别',
                        align: 'center',
                        key: 'itemType',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.itemType || '--')
                            ]);
                        }
                    },
                    {
                        title: '排查项目',
                        align: 'center',
                        key: 'apItemType',
                        minWidth: 120,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.apItemType || '--')
                            ]);
                        }
                    },
                    {
                        title: '排查内容',
                        align: 'center',
                        key: 'content',
                        minWidth: 200,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.content || '--')
                            ]);
                        }
                    },
                    {
                        title: '问题描述',
                        align: 'center',
                        key: 'remark',
                        minWidth: 200,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.remark || '--')
                            ]);
                        }
                    },
                    {
                        title: '隐患上报时间',
                        align: 'center',
                        key: 'createTimeStr',
                        minWidth: 150,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.createTimeStr || '--')
                            ]);
                        }
                    },
                    {
                        title: '整改完成时间',
                        align: 'center',
                        key: 'completionDate',
                        minWidth: 150,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.completionDate || '--')
                            ]);
                        }
                    },
                    {
                        title: '排查人',
                        align: 'center',
                        key: 'userName',
                        minWidth: 80,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.userName || '--')
                            ]);
                        }
                    },
                    {
                        title: '隐患级别',
                        align: 'center',
                        key: 'level',
                        minWidth: 90,
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.level || '--')
                            ]);
                        }
                    },
                    {
                        title: '是否整改',
                        align: 'center',
                        key: 'status',
                        minWidth: 90,
                        fixed: 'right',
                        render:(h,params)=>{
                            let color = params.row.status == '未消除'? 'red': 'green';
                            return h('div',[
                                h('span', {
                                    style: {
                                        color: color
                                    }
                                },params.row.status || '--')
                            ]);
                        }
                    },
                ],
                infos: [],
                dataToView: {}
            }
        },
        mounted(){
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 105;
            let user = sessionStorage('userId').getObject('userId');
            this.dataToView = {companyName: user.companyName, companyId: user.companyId};
            this.formInline.se_date = [this.getCurrentMonthFirst(), this.getCurrentMonthLast()];
            this.query();
            setTimeout(() => {
                this.$refs.existOrg.setCurrentOrg();
            }, 100);
        },
        methods: {
            query(){
                let user = sessionStorage('userId').getObject('userId');
                let data = {
                    orgId: user.companyId
                };
                if(this.formInline.se_date[0]!='' && this.formInline.se_date[1]!=''){
                    data.startDate = this.formatDate(new Date(this.formInline.se_date[0]), 'yyyy-MM-dd');
                    data.endDate = this.formatDate(new Date(this.formInline.se_date[1]), 'yyyy-MM-dd');
                }
                data = Object.assign(data,JSON.parse(JSON.stringify(this.formInline)));
                this.loading = true;
                this.$http.get(Api.getApsgInvestigationCount, {
                    params: data
                }).then(function(res){
                    if(res.data.status == 200){
                        this.infos = res.data.data;
                    }else{
                        this.$Message.error({
                            content: '查询失败',
                            duration: 4
                        });
                    }
                    this.loading = false;
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            cancel(){
                this.infos = [];
                this.formInline = {
                    se_date: []
                };
                setTimeout(() => {
                    this.$refs.existOrg.setCurrentOrg();
                }, 100);
            },
            setOrgName(data){
                this.formInline.orgId = data[data.length - 1];
            },
            exportExcel(){
                let user = sessionStorage('userId').getObject('userId');
                let data = {
                    orgId: user.companyId
                };
                if(this.formInline.se_date[0]!='' && this.formInline.se_date[1]!=''){
                    data.startDate = this.formatDate(new Date(this.formInline.se_date[0]), 'yyyy-MM-dd');
                    data.endDate = this.formatDate(new Date(this.formInline.se_date[1]), 'yyyy-MM-dd');
                }
                data = Object.assign(data,JSON.parse(JSON.stringify(this.formInline)));
                this.ifSpin = true;
                this.$http.get(Api.getApsgInvestigationCount + '/excel', {
                    params: data,
                    responseType: 'arraybuffer'
                }).then(function(res){
                    this.ifSpin = false;
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: "application/vnd.ms-excel"
                    })
                    aLink.href = URL.createObjectURL(blob);
                    aLink.download = "安全隐患上报内容汇总表.xlsx" //标题
                    aLink.click();
                    document.body.appendChild(aLink);
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },
            getCurrentMonthFirst(){
                let date = new Date();
                date.setDate(1);
                let month = parseInt(date.getMonth()+1);
                let day = date.getDate();
                if (month < 10) {
                    month = '0' + month
                }
                if (day < 10) {
                    day = '0' + day
                }
                return date.getFullYear() + '-' + month + '-' + day;
            },
            getCurrentMonthLast(){
                let date=new Date();
                let currentMonth=date.getMonth();
                let nextMonth=++currentMonth;
                let nextMonthFirstDay=new Date(date.getFullYear(),nextMonth,1);
                let oneDay=1000*60*60*24;
                let lastTime = new Date(nextMonthFirstDay-oneDay);
                let month = parseInt(lastTime.getMonth()+1);
                let day = lastTime.getDate();
                if (month < 10) {
                    month = '0' + month
                }
                if (day < 10) {
                    day = '0' + day
                }
                return date.getFullYear() + '-' + month + '-' + day;
            }
        }
    }
</script>

<style scoped>
    .demo-spin-icon-load{
        animation: ani-demo-spin 1s linear infinite;
    }
</style>
